import {Component, ElementRef, Renderer} from "@angular/core";
import {ActionSheetButton, ActionSheetOptions} from "./adp-action-sheet-options";
import {App, BLOCK_ALL, BlockerDelegate, GestureController, NavOptions, NavParams, ViewController} from "ionic-angular";
import * as _ from 'lodash';

@Component({
    selector: 'adp-action-sheet',
    templateUrl: 'adp-action-sheet.component.html'
})
export class AdpActionSheetComponent {
    private d: ActionSheetOptions;
    private cancelButton: ActionSheetButton;
    private _app: App;
    private gestureBlocker: BlockerDelegate;
    private computedTitle;

    constructor(private _viewCtrl: ViewController,
                private gestureCtrl: GestureController,
                private _elementRef: ElementRef,
                renderer: Renderer,
                params: NavParams,
                _app: App) {
        this.gestureBlocker = this.gestureCtrl.createBlocker(BLOCK_ALL);
        this._app = _app;
        this.d = params.data;
        renderer.setElementClass(_elementRef.nativeElement, `action-sheet-ios`, true);

        if (this.d.cssClass) {
            this.d.cssClass.split(' ').forEach(cssClass => {
                // Make sure the class isn't whitespace, otherwise it throws exceptions
                if (cssClass.trim() !== '') renderer.setElementClass(_elementRef.nativeElement, cssClass, true);
            });
        }

        let optionsLen = this.d.buttons.length;
        if (optionsLen > 4) {
            this.computedTitle = this.d.title ? `${this.d.title}(${String(optionsLen)})` : '标题';
        } else {
            this.computedTitle = this.d.title ? this.d.title : '标题';
        }
        let arr = [];
        this.d.buttons.forEach((item, index) => {
            if (item['cssClass'] || item['role'] === 'selected') {
                arr.push(index);
            }
        });
        for (let i = arr.length; i > 0; i--) {
            let button = _.cloneDeep(this.d.buttons[arr[i - 1]]);
            this.d.buttons.splice(arr[i - 1], 1);
            this.d.buttons.unshift(button);
        }
    }

    ionViewDidLoad() {
        this.d.buttons = this.d.buttons.map(button => {
            if (typeof button === 'string') {
                button = {text: button};
            }
            if (!button.cssClass) {
                button.cssClass = '';
            }
            switch (button.role) {
                case 'cancel':
                    this.cancelButton = button;
                    return null;
                case 'destructive':
                    button.cssClass = (button.cssClass + ' ' || '') + 'action-sheet-destructive';
                    break;
                case 'selected':
                    button.cssClass = (button.cssClass + ' ' || '') + 'action-sheet-selected';
                    break;
            }
            return button;
        }).filter(button => button !== null);
        setTimeout(() => {
            let nodeList = this._elementRef.nativeElement.querySelectorAll('.scroll-content');
            let len = nodeList.length;
            if (len > 0) {
                nodeList[len-1].scrollTop += 1;
            }
        }, 10);
    }

    ionViewWillEnter() {
        this.gestureBlocker.block();
        let backdrop = this._elementRef.nativeElement.querySelector('ion-backdrop');
        let wrapper = this._elementRef.nativeElement.querySelector('.action-sheet-wrapper');
        // let container = this._elementRef.nativeElement.querySelector('.action-sheet-container');
        backdrop.classList.add('present-backdrop');
        wrapper.classList.add('present-action-wrapper');
        // container.style.height = this.computedContainerHeight();
    }

    ionViewDidLeave() {
        this.gestureBlocker.unblock();
    }

    computedContainerHeight() {
        if (this.d.buttons.length > 5) {
            return 140 / 1080 * window.innerWidth * 7 +
                55 / 1080 * window.innerWidth
                + 'px';
        } else {
            return 140 / 1080 * window.innerWidth * (this.d.buttons.length + 2) +
                55 / 1080 * window.innerWidth
                + 'px';
        }
    }
    bdClick() {
        this.dismiss('backdrop');
    }

    dismiss(role: string): Promise<any> {
        let backdrop = this._elementRef.nativeElement.querySelector('ion-backdrop');
        let wrapper = this._elementRef.nativeElement.querySelector('.action-sheet-wrapper');

        backdrop.classList.remove('present-backdrop');
        wrapper.classList.remove('present-action-wrapper');

        const opts: NavOptions = {
            minClickBlockDuration: 400,
            duration: 50
        };
        return this._viewCtrl.dismiss(null, role, opts);
    }

    ngOnDestroy() {
        this.d = this.cancelButton = null;
        this.gestureBlocker.destroy();
    }

    click(button: ActionSheetButton) {
        let shouldDismiss = true;
        if (button.handler) {
            if (button.handler(button) === false) {
                shouldDismiss = false;
            }
        }
        if (shouldDismiss) {
            this.dismiss(button.role);
        }
    }

}
